#!/usr/bin/env python3
"""
创建测试项目数据的脚本
"""

import asyncio
import sys
import os
from datetime import datetime, timedelta
from bson import ObjectId

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from motor.motor_asyncio import AsyncIOMotorClient
from app.core.config import settings

async def create_test_projects():
    """创建测试项目数据"""
    try:
        # 连接数据库
        client = AsyncIOMotorClient(settings.MONGODB_URL)
        db = client[settings.MONGODB_DATABASE]
        
        # 检查是否已有项目数据
        existing_count = await db.projects.count_documents({})
        print(f"当前项目数量: {existing_count}")
        
        if existing_count > 0:
            print("数据库中已有项目数据，跳过创建")
            return
        
        # 创建测试用户（如果不存在）
        test_user = await db.users.find_one({"email": "admin@example.com"})
        if not test_user:
            test_user_id = ObjectId()
            await db.users.insert_one({
                "_id": test_user_id,
                "username": "admin",
                "email": "admin@example.com",
                "full_name": "系统管理员",
                "is_active": True,
                "is_superuser": True,
                "created_at": datetime.utcnow(),
                "updated_at": datetime.utcnow()
            })
            print("创建测试用户成功")
        else:
            test_user_id = test_user["_id"]
        
        # 测试项目数据
        test_projects = [
            {
                "name": "电商平台开发",
                "description": "构建现代化的电商平台，包含用户管理、商品管理、订单处理等功能",
                "status": "active",
                "priority": "high",
                "category": "web_development",
                "start_date": datetime.utcnow() - timedelta(days=30),
                "end_date": datetime.utcnow() + timedelta(days=60),
                "estimated_hours": 800,
                "budget": 150000.0,
                "tags": ["电商", "Web开发", "React", "Node.js"],
                "is_public": True,
                "is_archived": False,
                "created_by": test_user_id,
                "created_at": datetime.utcnow(),
                "updated_at": datetime.utcnow(),
                "members": [{"user_id": test_user_id, "role": "owner", "joined_at": datetime.utcnow()}]
            },
            {
                "name": "移动应用开发",
                "description": "开发跨平台移动应用，支持iOS和Android系统",
                "status": "planning",
                "priority": "medium",
                "category": "mobile_development",
                "start_date": datetime.utcnow() + timedelta(days=15),
                "end_date": datetime.utcnow() + timedelta(days=90),
                "estimated_hours": 600,
                "budget": 120000.0,
                "tags": ["移动开发", "React Native", "Flutter"],
                "is_public": True,
                "is_archived": False,
                "created_by": test_user_id,
                "created_at": datetime.utcnow(),
                "updated_at": datetime.utcnow(),
                "members": [{"user_id": test_user_id, "role": "owner", "joined_at": datetime.utcnow()}]
            },
            {
                "name": "数据分析平台",
                "description": "构建企业级数据分析和可视化平台",
                "status": "active",
                "priority": "high",
                "category": "data_science",
                "start_date": datetime.utcnow() - timedelta(days=15),
                "end_date": datetime.utcnow() + timedelta(days=45),
                "estimated_hours": 500,
                "budget": 100000.0,
                "tags": ["数据分析", "Python", "机器学习", "可视化"],
                "is_public": False,
                "is_archived": False,
                "created_by": test_user_id,
                "created_at": datetime.utcnow(),
                "updated_at": datetime.utcnow(),
                "members": [{"user_id": test_user_id, "role": "owner", "joined_at": datetime.utcnow()}]
            },
            {
                "name": "企业官网重构",
                "description": "重新设计和开发企业官方网站，提升用户体验",
                "status": "completed",
                "priority": "low",
                "category": "web_development",
                "start_date": datetime.utcnow() - timedelta(days=60),
                "end_date": datetime.utcnow() - timedelta(days=10),
                "estimated_hours": 200,
                "budget": 50000.0,
                "tags": ["网站重构", "UI/UX", "响应式设计"],
                "is_public": True,
                "is_archived": False,
                "created_by": test_user_id,
                "created_at": datetime.utcnow(),
                "updated_at": datetime.utcnow(),
                "members": [{"user_id": test_user_id, "role": "owner", "joined_at": datetime.utcnow()}]
            },
            {
                "name": "API网关服务",
                "description": "构建微服务架构的API网关，统一管理服务接口",
                "status": "on_hold",
                "priority": "medium",
                "category": "backend_development",
                "start_date": datetime.utcnow() + timedelta(days=30),
                "end_date": datetime.utcnow() + timedelta(days=120),
                "estimated_hours": 400,
                "budget": 80000.0,
                "tags": ["微服务", "API网关", "Docker", "Kubernetes"],
                "is_public": False,
                "is_archived": False,
                "created_by": test_user_id,
                "created_at": datetime.utcnow(),
                "updated_at": datetime.utcnow(),
                "members": [{"user_id": test_user_id, "role": "owner", "joined_at": datetime.utcnow()}]
            }
        ]
        
        # 插入测试项目
        result = await db.projects.insert_many(test_projects)
        print(f"成功创建 {len(result.inserted_ids)} 个测试项目")
        
        # 显示创建的项目
        for i, project in enumerate(test_projects):
            print(f"{i+1}. {project['name']} - {project['status']} - {project['priority']}")
        
        client.close()
        print("测试项目创建完成！")
        
    except Exception as e:
        print(f"创建测试项目失败: {str(e)}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    asyncio.run(create_test_projects())